
import { _decorator, Component, Node, UIOpacity, EventTouch, Vec2, Vec3, UITransform, v3, CameraComponent, Game, CCInteger } from 'cc';
import { EventMgr } from '../../../Framework/Scripts/Managers/EventMgr';

import { GameApp } from '../GameApp';
const { ccclass, property } = _decorator;



@ccclass('joyStick2')
export class joyStick2 extends Component {



    @property({ type: CCInteger, displayName: "半径" })
    maxRadius = 100;




    @property({ type: Node, displayName: "按钮组件" })
    control: Node | null = null;//按钮组件

    @property({ type: UIOpacity, displayName: "箭头" })//箭头
    indexArrow: UIOpacity = null!;

    @property({ type: Node, displayName: "整个摇杆" })//整个摇杆
    joyStick: Node = null!;

    public posVec3: Vec3 = new Vec3()//方向
    public degree: number = 0//角度

    public radians: number = 0

    private cameraUI: CameraComponent = null;



    onLoad() {
        this.cameraUI = GameApp.Instance.CanvasCamera

        this.indexArrow.opacity = 0





    }




    touchMove(p: Vec2): number {



        // 屏幕坐标转为世界坐标
        let world_point = this.cameraUI.screenToWorld(new Vec3(p.x, p.y));
        let pos = this.joyStick.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(world_point.x, world_point.y));
   
        // 如果触点长度小于我们规定好的最大半径
        if (pos.length() < this.maxRadius) {
            // 摇杆的坐标为触点坐标
            this.control.setPosition(pos.x, pos.y);
        } else {// 如果不
            // 将向量归一化
            let pos_ = pos.normalize();
            // 归一化的坐标 * 最大半径
            let x = pos_.x * this.maxRadius;
            let y = pos_.y * this.maxRadius;

            // 赋值给摇杆
            this.control.setPosition(x, y);
        }
        this.radians = Math.atan2(pos.y, pos.x)
        this.degree = this.radians / Math.PI * 180

        this.indexArrow.opacity = 255
        this.indexArrow.node.setRotationFromEuler(new Vec3(0, 0, this.degree - 90))

        return this.degree



    }

    onEnd(){
        this.control.setPosition(0,0)
    }




}

